<?php
	class WeixinModel extends Model{
	
		public $message;
		public $media;
		public $curl;
		public $access_token;
		
		public function _initialize() {		
			import('ORG.Util.weixin');
			$this->message = new ResponsePassive();	
			$this->media = new Media();
			$this->curl = new Curl();
			$this->access_token = new AccessToken();
		}
		public function send_welcome($from,$to,$welcome){
			echo $this->message->text($from,$to,$welcome);
		}
		public function send_phone($from,$to){
			$me = D('member')->where('wx_id ='.$from)->find();
			if($me == 0){
				echo $this->message->text($from,$to,"请输入您的手机号进行抽奖");
			}else{
				echo $this->message->text($from,$to,"您已经领取过奖励了！");
			}
			
		}	
		public function bind_companywx($key,$from,$to){
			$manage = D('company_manage')->where("wx_id = '".$from."' AND is_del = 0")->find();
			if(!empty($manage)){
				exit($this->message->text($from,$to,'您已经绑定过企业！'));
			}
			$bind = D('weixin_bind')->where('code = '.$key)->find();
			if(!empty($bind)&&$bind['isidentify']==0){
				$manage = array(
							'cid' => $bind['cid'],
							'wx_id' => $from,
							'bindline' => time()
						);
				$data['manageid'] = D('company_manage')->add($manage);
				$data['isidentify'] = 1;
				D('weixin_bind')->where('code = '.$key)->save($data);
				unlink($bind['path']);
				echo $this->message->text($from,$to,'绑定成功');
			}elseif(!empty($bind)&&$bind['isidentify']==1){
				unlink($bind['path']);
				echo $this->message->text($from,$to,'该二维码已经验证过，请刷新页面');
			}else{
				echo $this->message->text($from,$to,'请重新扫描二维码');
			}
		}
		
		public function reply_companywx($key,$from,$to){
			$map['wx_id'] = $to;
			$company = D('company_wx')->where($map)->find();
			$reply_where = array(
								'cid' => $company['cid'],
								'key' => $key,
								'is_del' => 0
							);
			$reply = D('weixin_reply')->where($reply_where)->order('updateline DESC')->find();
			if(empty($reply)){
				exit();
			}
			if($reply['type']==1){
				$message = D('weixin_reply_word')->where('rid = '.$reply['reply_id'])->find();
				echo $this->message->text($from,$to,$message['content']);
			}else{
				$message = D('weixin_reply_image')->where('reply_id = '.$reply['reply_id'])->find();
				if($message['type']==1){
					$reply_item = unserialize($message['content']);
					$pic = get_img_url($reply_item['picaid']);
					$reply_item['article_url'] = 'http://www.rencailaile.com'.U('Companywx/read',array('article_id'=>base64_encode($reply['reply_id'].'-0')));
					$item[] = $this->message->newsItem($reply_item['title'],$reply_item['description'],$pic['url'],$reply_item['article_url']);
				}else{
					$i = 0;
					$reply_item[$i] = unserialize($message['content']);
					$reply_item[$i]['picurl'] = get_img_url($reply_item[$i]['picaid']);
					$reply_item[$i]['article_url'] = 'http://www.rencailaile.com'.U('Companywx/read',array('article_id'=>base64_encode($reply['reply_id'].'-'.$i)));
					$reply_item_more = unserialize($message['content_more']);
					foreach($reply_item_more as $k => $v){
						$i++;
						$v['picurl'] = get_img_url($v['picaid']);
						$v['article_url'] = 'http://www.rencailaile.com'.U('Companywx/read',array('article_id'=>base64_encode($reply['reply_id'].'-'.$i)));
						$reply_item[$i] = $v;
					}
					foreach($reply_item as $k =>$v){
						$item[] = $this->message->newsItem($v['title'],$v['description'],$v['picurl']['url'],$v['article_url']);
					}
				}
				echo $this->message->news($from,$to,$item);
			}
		}
		
		public function diyindex_companywx($key,$from,$to){
			$data['brand_name'] = $key;
			$brand = D('brand')->where($data)->find();
			if(!empty($brand)){
				$company = D('company_info')->where('is_del = 0 AND status = 1')->select();
				foreach ($company as $k => &$v) {
					$bra = explode(',', $v['brand']);
					if (in_array($brand['bid'],$bra)){
						$v['logo'] = get_img_url($v['logo']);
						$companyname = D('company')->where(array('cid'=>$v['cid']))->find();
						$url = 'http://www.rencailaile.com'.U('Companyreview/index',array('cid'=>$v['cid']));
						$item[] = $this->message->newsItem($companyname['company_name'],'',$v['logo']['url'],$url);
					}
				}
				echo $this->message->news($from,$to,$item);
			}
		}
		
		public function diycontrol($from,$to){
			$title = '点击进入微官网管理';
			$picurl = 'http://www.baidu.com/img/baidu_jgylogo3.gif';
			$url = 'http://rencailaile.com'.U('Companycontrol/index',array('from'=>$from));
			$item[] = $this->message->newsItem($title,'sdfasd',$picurl,$url);
			echo $this->message->news($from,$to,$item);
		}
		
		public function supplyresume($from,$to){
			$uid = $this->getuid_byopenid($from,$to);
			//如果用户初始化了但没有上传头像则提示上传头像
			$info = D('member_info')->where('uid = '.$uid)->find();
			if(empty($info['face'])||$info['face']==0){
				$this->uploadface($from,$to);
				exit();
			}
			//如果用户初始化了上传了头像没有简历则初始化简历并提示上传语音
			$resume = D('resume')->where('uid = '.$uid)->find();
			if(empty($resume)){
				$resume_info = array(
							'uid' => $uid,
							'ctime' => time()
						);
				D('resume')->add($resume_info);
				$this->uploadvoice($from,$to);
				exit();
			}else{
				if($resume['voice']==0){
					$this->uploadvoice($from,$to);
					exit();
				}
			}
			//如果用户初始化了上传了头像上传了语音则提示填写简历
			if($info['status']){
				$text = '<a href="http://www.rencailaile.com/weixin.php?s=/Resume/resume">点击进入简历管理</a>';
				echo $this->message->text($from,$to,$text);
				exit();
			}else{
				$text = '请点击<a href="http://www.rencailaile.com/weixin.php?s=/Resume/resume/wxmanage/'.$wx_id.'/wxid/'.$from.'">完善基本信息</a>';
				echo $this->message->text($from,$to,$text);
			}
		}
		
		public function uploadface($from,$to){
			$uid = $this->getuid_byopenid($from,$to);
			if($uid){
				$data = array(
							'uid' => $uid,
							'type' => 'face',
							'createline' => time()
						);
				D('member_uploadstatus')->add($data);
				$text = '请上传你的近照，如果不知道怎么上传，请点击<a href="http://www.rencailaile.com/weixin.php?s=/Companywx/read/article_id/MzUtMA==">查看教程</a>';
				echo $this->message->text($from,$to,$text);
			}else{
				echo $this->message->text($from,$to,'尚未创建账户');
			}
		}
		
		public function uploadvoice($from,$to){
			$uid = $this->getuid_byopenid($from,$to);
			if($uid){
				$data = array(
							'uid' => $uid,
							'type' => 'voice',
							'createline' => time()
						);
				D('member_uploadstatus')->add($data);
				$text = '请切换到语音模式并按住“按住说话”录下你的姓名，年龄，身高/体重，简短的工作经历介绍（如：有3年半的工作经验，2013年在**服装公司做了2年的服装导购，1年半的鞋包销售经验）；想在哪个商圈找什么行业工作（如：想在人民广场或者1号线沿线找服装、鞋包类导购工作），如果不知道怎么用，请点击<a href="http://www.rencailaile.com/weixin.php?s=/Companywx/read/article_id/MzQtMA==">查看教程</a>';
				echo $this->message->text($from,$to,$text);
			}else{
				echo $this->message->text($from,$to,'尚未创建账户');
			}
		}
		
		public function getvoice_companywx($message,$from,$to){
			$uid = $this->getuid_byopenid($from,$to);
			if($uid){
				//检测录制音频阀门是否打开或在有效期内
				$uploadface = D('member_uploadstatus')->where('uid = '.$uid.' AND type = "voice"')->order('createline DESC')->find();
				if(time()-$uploadface['createline']<=300){
					D('member_uploadstatus')->where('uid = '.$uid.' AND type = "voice"')->delete();
					$this->defineappauth($from,$to);
					$voice = $this->media->download($message[0]);
					$temp_path = 'data/temp_voice/';
					$temp_name = date('Y-m-d-',time()).rand(1000,9999);
					$temp_file = $temp_path.$temp_name.'.'.$message[1];
					$outputfile = $temp_path.$temp_name.'.mp3';
					$open=fopen($temp_file,"w");
					fwrite($open,$voice);
					fclose($open);
					exec("ffmpeg -i ".$temp_file.' '.$outputfile);
					if(file_exists($outputfile)) {
						$vid = uploadvoice('voice',$outputfile);
						if($vid){
							unlink($temp_file);
							unlink($outputfile);
						}
						$resume = D('resume')->where('uid = '.$uid)->find();
						if(!empty($resume)){
							$resume['voice'] = $vid;
							$edit = 1;
							$result = D('resume')->where('uid = '.$uid)->save($resume);
						}else{
							$resume = array('uid'=>$uid,'voice'=>$vid);
							$result = D('resume')->add($resume);
						}
						$minfo = D('member_info')->where('uid = '.$uid)->find();
						if($result){
							if($minfo['truename']==""){
								if($edit == 1){
									echo $this->message->text($from,$to,'恭喜，您的语音简历修改成功，如需更改，只要输入“修改语音简历”并重新录制即可。请点击<a href="http://www.rencailaile.com'.U('Resume/resume_01').'">完善基本信息</a>');
								}else{
									echo $this->message->text($from,$to,'恭喜，您的语音简历上传成功，如需更改，只要输入“修改语音简历”并重新录制即可。请点击<a href="http://www.rencailaile.com'.U('Resume/resume_01').'">完善基本信息</a>');
								}
							}else{
								if($edit == 1){
									echo $this->message->text($from,$to,'恭喜，您的语音简历修改成功，如需更改，只要输入“修改语音简历”并重新录制即可。请点击<a href="http://www.rencailaile.com'.U('Resume/resume').'">查看简历</a>');
								}else{
									echo $this->message->text($from,$to,'恭喜，您的语音简历上传成功，如需更改，只要输入“修改语音简历”并重新录制即可。请点击<a href="http://www.rencailaile.com'.U('Resume/resume').'">查看简历</a>');
								}
							}
							
						}else{
							echo $this->message->text($from,$to,'录音添加失败');
						}
					} else {
						echo $this->message->text($from,$to,'音频格式转换失败，请联系管理员');
					}
				}
			}else{
				echo $this->message->text($from,$to,'尚未创建账户');
			}
		}
		
		public function getface_companywx($mediaid,$from,$to){
			$uid = $this->getuid_byopenid($from,$to);
			if($uid){
				//检测上传头像阀门是否打开或在有效期内
				$uploadface = D('member_uploadstatus')->where('uid = '.$uid.' AND type = "face"')->order('createline DESC')->find();
				if(time()-$uploadface['createline']<=300){
					D('member_uploadstatus')->where('uid = '.$uid.' AND type = "face"')->delete();
					$this->defineappauth($from,$to);
					$face = $this->media->download($mediaid);
					$temp_file = 'data/temp_face/'.date('Y-m-d-',time()).rand(1000,9999).'.jpg';
					$open=fopen($temp_file,"w");
					fwrite($open,$face);
					fclose($open);
					$aid = uploadface('face',$temp_file);
					if($aid){
						unlink($temp_file);
					}
					$user['face'] = $aid;
					$ed = D('member_info')->where('uid = '.$uid)->find();
					$re = D('resume')->where('uid = '.$uid)->find();
					$result = D('member_info')->where('uid = '.$uid)->save($user);
					if($result){
						$data = array(
									'uid' => $uid,
									'type' => 'voice',
									'createline' => time()
								);
						D('member_uploadstatus')->add($data);
						if($ed['truename']==""){
								if($re['voice'] == ""){
									echo $this->message->text($from,$to,'恭喜，您的近照上传成功，如需更改，只要输入“修改照片”并重新上传即可。请切换至语音模式并按住”按住说话“录下你的自我介绍，如果不知道怎么用，请点击<a href="http://www.rencailaile.com/weixin.php?s=/Companywx/read/article_id/MzQtMA==">查看教程</a>');
								}else{
									echo $this->message->text($from,$to,'恭喜，您的近照上传成功，如需更改，只要输入“修改照片”并重新上传即可。请点击<a href="http://www.rencailaile.com'.U('Resume/resume_01').'">完善基本信息</a>');
								}
							}else{
								echo $this->message->text($from,$to,'恭喜，您的近照上传成功，如需更改，只要输入“修改照片”并重新上传即可。请点击<a href="http://www.rencailaile.com'.U('Resume/resume').'">查看简历</a>');
							}
					}else{
						echo $this->message->text($from,$to,'头像添加失败'.$uid);
					}
				}
			}else{
				echo $this->message->text($from,$to,'尚未创建账户');
			}
		}
		
		public function getaccess_login($code){
			$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.C('WX_APPID').'&secret='.C('WX_APPKEY').'&code='.$code.'&grant_type=authorization_code';
			$return = $this->curl->callWebServer($url, '', 'GET', 0);
			return (array)json_decode($return);
		}
		
		public function getuserinfo_login($access_token,$openid){
			$url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
			$return = $this->curl->callWebServer($url, '', 'GET', 0);
			return (array)json_decode($return);
		}
		
		public function binduser_login($userinfo){
			$where['union'] = $userinfo['unionid'];
			$user = D('member')->where($where)->find();
			if(empty($user)){
				//新用户记录写入member表
				$member = array(
							'union' => $userinfo['unionid'],
							'wx_id' => $userinfo['openid'],
							'is_active' => 1,
							'ctime' => time(),
							'regip' => '127.0.0.1',
							'lastlogin' => time()
						);
				$user['uid'] = D('member')->add($member);
				$member_info = array(
								'uid' => $user['uid'],
								'ctime' => time()
							);
				$user_info = D('member_info')->add($member_info);
				$openids = array(
								'uid' => $user['uid'],
								'openid' => $userinfo['openid']
							);
				$openids = D('member_openids')->add($openids);
			}
			$result = D('Member')->_locallogin($user['uid']);
			if($result){
				return true;
			}else{
				return false;
			}
		}
		
		public function getuid_byopenid($from,$to){
			//查找是否有记录
			$openid = D('member_openids')->where('openid = "'.$from.'"')->find();
			if(empty($openid)){
				$redirect_uri = urlencode('http://www.rencailaile.com'.U('Login/getopenid',array('openid'=>$from)));
				$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.C('WX_APPID').'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
				echo $this->message->text($from,$to,'<a href="'.$url.'">点击进行授权</a>');
			}else{
				return $openid['uid'];
			}
		}
		
		public function location_companywx($mapx,$mapy,$from,$to){	
			$user = D('member')->where('wx_id = "'.$from.'"')->find();
			if(!empty($user)){
				$data['map_x'] = $mapx;
				$data['map_y'] = $mapy;
				D('member')->where('uid = '.$user['uid'])->save($data);
			}
			$url = 'http://www.rencailaile.com'.U('Hiring/nearhiring');
			echo $this->message->text($from,$to,'<a href="'.$url.'">点击查看附近职位</a>');
		}
		
		public function getmax($myLat,$myLng){
			$range = 180 / pi() * 1 / 6372.797;     //里面的 1 就代表搜索 1km 之内，单位km  
			$lngR = $range / cos($myLat * pi() / 180);  
			$maxLat = $myLat + $range;//最大纬度  
			$minLat = $myLat - $range;//最小纬度  
			$maxLng = $myLng + $lngR;//最大经度  
			$minLng = $myLng - $lngR;//最小经度 
			return array($maxLat,$minLat,$maxLng,$minLng);
		}
	
		public function defineappauth($from,$to){
			$company_info = D('company_wx')->where('wx_id = "'.$to.'"')->find();
			if(empty($company_info)){
				echo $this->message->text($from,$to,'该企业未在后台绑定公众号，请通知该企业');exit();
			}else{
				if(empty($company_info['wx_appid'])||empty($company_info['wx_appkey'])){
					echo $this->message->text($from,$to,'该企业公众号信息未填写完整或非认证公众号，该功能无法使用，请通知该企业');exit();
				}else{
					define('WECHAT_APPID',$company_info['wx_appid']);
					define('WECHAT_APPSECRET',$company_info['wx_appkey']);
				}
			}
		}
		
		public function addnewid($uid,$wxid,$from){
			$map[$wxid] = $from;
			$result = D('member')->where('uid = '.$uid)->save($map);
			if($result){
				return true;
			}else{
				return false;
			}
		}
			
	}
?>
